# -*- coding: utf-8 -*

import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from travel import TravelPlanner

import geohelper
import datastore

def getAllSpots(request):
    spots = []
    rawSpots = request.get('SelectedSpots')
    spots = rawSpots.split(';')
    spots = filter(lambda x: x != '', spots)
    return spots

def getOrdered(request):
    if request.get('Ordered') == '':
        return False
    return True
    
class ResultPage(webapp.RequestHandler):
    def post(self):
        spots = getAllSpots(self.request)
        ordered = getOrdered(self.request)

        '''
        home = geohelper.getHomeSpot()
        stops = geohelper.getNearbyStops(home.location)
        for stop in stops:
            self.response.out.write(stop.name + '<br>')
        '''
        
        
        planner = TravelPlanner(spots, ordered)

        templateDict = {
            'spots': planner.getSpotsOrder(), 
            'timeTable': planner.getTimeTable(),
        }
        
        '''
        home = geohelper.getHomeSpot()
        stops = geohelper.getNearbyStops(home.location)
        stops = geohelper.getNearbyStops(home.location)
        stops = geohelper.getNearbyStops(home.location)
        for stop in stops:
            print stop.name.encode('utf-8')
        '''
        '''
        home = datastore.HotSpot.all().filter('name =', u'資工系館').fetch(1)[0]
        stop1 = datastore.Stop.all().filter('name =', u'科技大樓站').fetch(1)[0]
        stop2 = datastore.Stop.all().filter('name =', u'公館站').fetch(1)[0]
        goal = datastore.HotSpot.all().filter('name =', u'中正紀念堂').fetch(1)[0]
        timeHomeStop1 = geohelper.getWalkingTime(home.location, stop1.location)
        timeHomeStop2 = geohelper.getWalkingTime(home.location, stop2.location)
        timeStop1Goal = geohelper.getWalkingTime(stop1.location, goal.location)
        timeStop2Goal = geohelper.getWalkingTime(stop2.location, goal.location)
        print '科技大樓站', (timeHomeStop1 + timeStop1Goal)
        print '公館站', (timeHomeStop2 + timeStop2Goal)
        '''

        path = os.path.join(os.path.dirname(__file__), 'result.html')
        self.response.out.write(template.render(path, templateDict))
